import axios from "axios";
import store from "@/store";
import Vue from "vue";
import { Message } from "element-ui";
import { isCheckTimeout } from "@/utils/auth";
Vue.prototype.$message = Message;

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 统一注入token
    if (store.getters.token) {
      // token是否超时
      if (isCheckTimeout()) {
        store.dispatch("user/logout");
        return Promise.reject(new Error("token 失效"));
      }

      config.headers.MyAuthorization = store.getters.token;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { code, msg, data, token, type } = response.data;
    //   要根据success的成功与否决定下面的操作
    if (code === 200) {
      if (token) {
        return { data, token, type };
      }
      return data;
    } else {
      // 业务错误
      Vue.prototype.$message({
        message: msg,
        type: "error",
      });
      if (msg.indexOf('token') != -1) {
        store.dispatch("user/logout");
      }
      // 提示错误消息
      return Promise.reject(new Error(msg));
    }
  },
  (error) => {
    // console.log(1);
    // TODO: 将来处理 token 超时问题
    Vue.prototype.$message({
      message: error,
      type: "error",
    });
    return Promise.reject(error);
  }
);

export default service;
